package com.icen.utils.ksoap;

import java.util.ArrayList;
import java.util.Map;

import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;
import android.util.Log;

/**
 * KSOAP Utils for WebService
 * 
 * @author IcenHan 2015-01-21
 * 
 */
public class KsoapUtils extends AsyncTask<String, Object, Object> {
	private String mWsdlURL; // 连接地址
	private String mNameSpace; // 命名空间
	private String mMethodName; // 方法名

	private boolean mIsShowLog = false; // 是否打印日志
	private boolean mDotNet = true; // 是否开启DOTNET
	private boolean mDebug = false; // 是否开启DEBUG模式
	private int mTimout = 15 * 1000; // 超时设置

	private KsoapParams<String, Object> mKsoapParams = null;
	private OnRequestCallBack mOnRequestCallBack = null;

	public KsoapUtils(String wsdlURL, String nameSpace) {
		this.mWsdlURL = wsdlURL;
		this.mNameSpace = nameSpace;
	}

	public void sendRequest(String methodName,
			KsoapParams<String, Object> ksoapParams,
			OnRequestCallBack onRequestCallBack) {
		this.mMethodName = methodName;
		this.mKsoapParams = ksoapParams;
		this.mOnRequestCallBack = onRequestCallBack;
		this.execute();
	}

	@Override // 异步任务开始
	protected void onPreExecute() {
		super.onPreExecute();
	}
	
	@Override // 异步任务执行过程
	protected Object doInBackground(String... params) {
		return createKsoapRequest();
	}
	
	@Override // 异步任务执行结果
	protected void onPostExecute(Object result) {
		if(result != null && result instanceof Exception) {
			mOnRequestCallBack.onFailure((Exception)result);
		}else{
			mOnRequestCallBack.onSuccess(result);
		}
	}
	
	private Object createKsoapRequest() {
		if (mIsShowLog) {
			Log.i("[KsoapUtils|WsdlURL]", mWsdlURL);
			Log.i("[KsoapUtils|NameSpace]", mNameSpace);
			Log.i("[KsoapUtils|MethodName]", mMethodName);
		}

		SoapObject soap = new SoapObject(mNameSpace, mMethodName);
		// 添加参数
		if (mKsoapParams != null && !mKsoapParams.isEmpty()) {
			for (Map.Entry<String, Object> entry : mKsoapParams.entrySet()) {
				soap.addProperty(entry.getKey(), entry.getValue());
			}
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = mDotNet;
		envelope.bodyOut = soap;
		envelope.setOutputSoapObject(soap);

		// 发起Web请求
		HttpTransportSE http = new HttpTransportSE(mWsdlURL, mTimout);
		http.debug = mDebug;
		ArrayList<HeaderProperty> headerPropertyArrayList = new ArrayList<HeaderProperty>();
		headerPropertyArrayList.add(new HeaderProperty("Connection", "close"));
		
		Object requestResult = null;
		try {
			http.call(mNameSpace + mMethodName, envelope,
					headerPropertyArrayList);
			requestResult = envelope.getResponse();
			if (requestResult == null) {
				requestResult = envelope.bodyIn;
			}
			if (mIsShowLog) {
				Log.i("[KsoapUtils|RequestResult]", requestResult + "");
			}
		} catch (Exception e) {
			requestResult = e;
			if (mIsShowLog) {
				Log.i("[KsoapUtils|Exception]", e.toString());
			}
		} finally {
			// 请求完成后断开连接
			System.setProperty("http.keepAlive", "false");
		}
		return requestResult;
	}

	/**
	 * 回调接口
	 */
	public interface OnRequestCallBack {
		void onSuccess(Object result);

		void onFailure(Exception e);
	}

	/**
	 * 是否打印日志：默认false
	 * 
	 * @param isShowLog
	 */
	public void setIsShowLog(boolean isShowLog) {
		this.mIsShowLog = isShowLog;
	}

	/**
	 * 是否开启DOTNET访问：默认true
	 * 
	 * @param dotNet
	 */
	public void setDotNet(boolean dotNet) {
		this.mDotNet = dotNet;
	}

	/**
	 * 是否开启DEBUG模式：默认false
	 * 
	 * @param debug
	 */
	public void setDebug(boolean debug) {
		this.mDebug = debug;
	}

	/**
	 * 设置超时时间（单位：毫秒）：默认15*1000毫秒
	 * 
	 * @param timout
	 */
	public void setTimout(int timout) {
		this.mTimout = timout;
	}

}
